package com.github.jcooky.structure;

public class LinkedListSequence implements Sequence {
	private LinkedList list ;
	
	public LinkedListSequence() {
		this(new LinkedList());
	}
	
	public LinkedListSequence(LinkedList list) {
		this.list = list;
	}

	public int size() {
		return list.size();
	}

	public boolean isEmpty() {
		return list.isEmpty();
	}

	public Node first() {
		return list.first();
	}

	public Node last() {
		return list.last();
	}

	public Node prev(Node p) {
		return list.prev(p);
	}

	public Node next(Node p) {
		return list.next(p);
	}

	public void set(Node p, Object e) {
		list.set(p, e);
	}

	public void addBefore(Node p, Object e) {
		list.addBefore(p, e);
	}

	public void addAfter(Node p, Object e) {
		list.addAfter(p, e);
	}

	public void addFirst(Object e) {
		list.addFirst(e);
	}

	public void addLast(Object e) {
		list.addLast(e);
	}

	public Object remove(Node p) {
		return list.remove(p);
	}

	public Object get(int i) {
		return atIndex(i).element();
	}

	public Object set(int i, Object e) {
		Node node = atIndex(i);
		Object o = node.element();
		node.setElement(e);
		
		return o;
	}

	public void add(int i, Object e) {
		list.addBefore(atIndex(i), e);
	}

	public Object remove(int i) {
		return list.remove(atIndex(i));
	}

	public Node atIndex(int i) {
		int index = 0;
		for (Node node = list.first(); node != list.next(list.last()); node = node.getNext(), ++index) {
			if (i == index) {
				return node;
			}
		}
		
		return null;
	}

	public int indexOf(Node p) {
		int i = 0;
		for (Node node = list.first(); node != list.next(list.last()); node = node.getNext(), ++i) {
			if (node.equals(p)) {
				return i;
			}
		}
		
		return -1;
	}

	public Iterator iterator() {
		return list.iterator();
	}
}
